var util = require('../../../libs/util.js');
var moment = require('../../../libs/moment.min.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    change_date:moment().format('YYYY-MM-DD'),
    imgList:[],
    formType : 'add',
    flowItem:1,
    itemData:[],
    roleList:util.roleList
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    //更新数据
    that.setData({
      server:app.server
    });
    this.loadData();
  },
  addFlowItem:function(e){
    var that = this;
    var itemData = that.data.itemData;
    itemData.push({
      nodename:'',
      roles:'',
      rolesName:'',
      users:'',
      usersName:''
    })
    this.setData({
      itemData:itemData,
      flowItem: this.data.flowItem + 1
    })
  },
  deleteFlowItem:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    var itemData = that.data.itemData;
    var _itemData = [];
    for(var i=0;i<itemData.length;i++){
      if(index != i){
        _itemData.push(itemData[i])
      }
    }
    this.setData({
      itemData:_itemData,
      flowItem: this.data.flowItem - 1
    })
  },
  changeMode:function(e){
    this.setData({
      mode:e.currentTarget.dataset.mode
    })
    //this.loadData();
 },
  switchChange(e) {
    console.log(e)
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  chooseCheckbox(e) {
    var items = this.data.roleList;
    var value = e.currentTarget.dataset.value;
    var name = e.currentTarget.dataset.name;
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      if (items[i].name == name) {
        items[i].checked = !items[i].checked;
        break
      }
    }
    this.setData({
      roleList: items
    })
  },
  rolesChange(e) {
    console.log(e);
    var that = this;
    var index = this.data.itemIndex;
    var roleList = this.data.roleList;

    var itemData = that.data.itemData;
    if(!itemData[index]){
      itemData[index] = {
        nodename:'',
        roles:'',
        rolesName:'',
        users:'',
        usersName:''
      }
    }
    var _role = [],_name = [];
    for(var i=0;i<roleList.length;i++){
      if(roleList[i].checked){
        _role.push(roleList[i].role);
        _name.push(roleList[i].name);
      }
    }
    for(var i=0;i<itemData.length;i++){
      if(index == i){
        itemData[index].roles = _role.join(",");
        itemData[index].rolesName = _name.join(",");
      }
    }
    this.setData({
      itemData:itemData,
      modalName: 'detailModal',
      modalTitle: '新增流程',
      modalType:'add'
    })
    // this.setData({
    //   position_index: e.detail.value
    // })
  },
  bindInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    
    var index = e.currentTarget.dataset.index;
    if(isNaN(index) == false){
      var itemData = that.data.itemData;
      if(!itemData[index]){
        itemData[index] = {
          nodename:'',
          roles:'',
          rolesName:'',
          users:'',
          usersName:''
        }
      }
      itemData[index][item] = e.detail.value;
      this.setData({
        itemData: itemData
      })
    }else{
      item_value[item] = e.detail.value;
      this.setData(item_value);
    }
    

  },
  search: function () {
    this.loadData();
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '请稍候...',
    });
    util.getData("/atapi/erp/workflow/list", {
      'CO_ID': app.globalData.CO_ID,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize
    }, function (res, error) {
      console.log(res); console.log(error)
      setTimeout(function(){
        wx.hideLoading();
      },100);
      if (res.data.success) {
        var count = res.data.data[1][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        that.setData({
          dataList: res.data.data[0],
          count: count,
          pageNumber: pageNumber,
          page: that.data.page == 0 ? 1 : that.data.page
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          dataList: []
        });
      }
    });
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: e.currentTarget.dataset.title,
      modalType:e.currentTarget.dataset.type,
      itemIndex:e.currentTarget.dataset.index
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  selectUsers:function(e){
    this.setData({
      itemIndex:e.currentTarget.dataset.index
    })
    wx.navigateTo({
      url: '/pages/enterprise/user_select'
    })
  },
  flowForm:function(e){
    this.setData({
      currentId:e.currentTarget.dataset.id
    })
    wx.navigateTo({
      url: '/pages/erp/workflow/form_info?id='+e.currentTarget.dataset.ffid||''
    })
  },
  editForm:function(e){
    var that = this;
    var dataList = that.data.dataList;
    var id = e.currentTarget.dataset.id;
    var currentData = {},itemData = [];
    for(var i=0;i<dataList.length;i++){
      if(dataList[i].ID == id){
        currentData = dataList[i];
      }
    }
    var flow_node = String(currentData.flow_node).split(">>");console.log(flow_node)
    var NODE_ROLE = String(currentData.NODE_ROLE).split("$");
    var NODE_ROLE_NAME = String(currentData.NODE_ROLE_NAME).split("$");
    if(flow_node.length > 0){
       for(var i=0;i<flow_node.length;i++){
        var _roles = String(NODE_ROLE[i]).split("|");
        var _name = String(NODE_ROLE_NAME[i]).split("|");
        itemData.push({
          nodename:flow_node[i],
          roles:_roles[0],
          rolesName:_name[0],
          users:_roles[1],
          usersName:_name[1]
        })
       }
    }
    this.setData({
      currentData:currentData,
      flowItem:flow_node.length,
      name:currentData.NAME,
      itemData:itemData,
      modalName: 'detailModal',
      modalTitle: '修改流程',
      modalType:'add',
      formType:'edit'
    })
  },
  submitFormData:function(){
    var that = this;

    var formData = {};
    formData.NAME = that.data.name||'';
    if(formData.NAME == ''){
      wx.showToast({
        title: "请填写流程名称",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }

    var itemData = that.data.itemData;
    if(itemData.length == 0){
      wx.showToast({
        title: "请填写节点",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    for(var i=0;i<itemData.length;i++){
       if(itemData[i].nodename == ''){
        wx.showToast({
          title: "节点名称有误",
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
       }
       if(itemData[i].roles == '' && itemData[i].users == ""){
        wx.showToast({
          title: "未选择审核对象",
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
       }
    }
    formData.item = JSON.stringify(itemData);

    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    formData.CO_ID = app.globalData.CO_ID;
    formData.ADD_USER = app.globalData.user_id;
    if (that.data.formType == 'add'){
      util.postData("/atapi/erp/workflow/new", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }else{
      formData.id = that.data.currentData.ID;
      util.putData("/atapi/erp/workflow/edit", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "编辑成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "编辑失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }
    
  },
  deleteData:function(){
    var that = this;
    var _currentData = that.data._currentData;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除吗？',
      success (res) {
        if (res.confirm) {
            util.deleteData("/atapi/erp/workflow/delete", {
              id: _currentData.ID,
              user_id:app.globalData.user_id,
              CO_ID:app.globalData.CO_ID,
              truename:app.globalData.truename,
              logs:that.data.plate+','+_currentData.name+','+_currentData.site+','+_currentData.fee+','+_currentData.upkeep_time+','+_currentData.user_id
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function(){
                      that.hideModal();
                        that.loadData();
                    },3000)
                  }
                });
              }
            });
          }
        }
        })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'selected_userdata',
      success: function (res) {
        console.log(res)
        if (res.data) {
          var data = res.data;
          var users = [],usersName=[];
          for(var i=0;i<data.length;i++){
            users.push(data[i].value);
            usersName.push(data[i].name);
          }
          var index = that.data.itemIndex;
          var itemData = that.data.itemData;
          if(!itemData[index]){
            itemData[index] = {
              nodename:'',
              roles:'',
              rolesName:'',
              users:'',
              usersName:''
            }
          }
          itemData[index].users = users.join(",");
          itemData[index].usersName = usersName.join(",");
          that.setData({
            itemData: itemData
          })
          wx.removeStorage({
            key: 'selected_userdata',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'selected_formdata',
      success: function (res) {
        console.log(res)
        if (res.data) {
          var data = res.data;
          console.log(data)
          util.putData("/atapi/erp/workflow/bindform", {
            user_id:app.globalData.user_id,
            CO_ID:app.globalData.CO_ID,
            truename:app.globalData.truename,
             id:that.data.currentId,
             formdata:JSON.stringify(data)
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading()
            if (res.data.success) {
              wx.showToast({
                title: "关联成功",
                icon: "success",
                duration: 3000,
                success: function () {
                  setTimeout(function () {
                    that.loadData()
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: "关联失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
          wx.removeStorage({
            key: 'selected_formdata',
            success: function (res) {
            }
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})